﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NetJavap
{
    public delegate void OpCodeExecuteAction(JVM.JVMCodeRunner currentRuntime);
    public class JOpcode : ClassMember
    {
        private Byte _opcode;
        private Byte _length;
        private Byte[] _otherBytes;
        private Byte[] _otherBytesReverse;

        private OpCodeExecuteAction _executeAct;

        public Byte Opcode { get { return this._opcode; } }
        public OpCodeExecuteAction ExecuteAction { get { return this._executeAct; } }
        public Byte[] OtherBytes { get { return this._otherBytes; } }

        public JOpcode(BinaryReader reader, JavaClass cls, Byte length, OpCodeExecuteAction execAct)
            : base(cls)
        {
            this._opcode = reader.ReadByte();
            this._otherBytes = reader.ReadBytesRequired(length);
            this._length = length;
            this._executeAct = execAct;
        }

        public override string ToString()
        {
            return JOpcodeBuilder.GetMnemonic(this._opcode);
        }

        private void ReverseData()
        {
            if (this._otherBytesReverse == null)
            {
                this._otherBytesReverse = this._otherBytes.Reverse();
            }
        }

        public Byte GetByteValue()
        {
            return _otherBytes[0];
        }

        public UInt16 GetUInt16Value()
        {
            this.ReverseData();
            return BitConverter.ToUInt16(this._otherBytesReverse, 0);
        }

        public Int16 GetInt16Value()
        {
            this.ReverseData();
            return BitConverter.ToInt16(this._otherBytesReverse, 0);
        }

    }
}
